<!-- Select Organization -->
<!-- Author: Edwin -->
<template>
  <div style="width:100%;">
    <el-popover v-model="deptListVisible"
                ref="deptListPopover"
                placement="bottom-start"
                trigger="click"
                width="100%">
      <el-tree :data="deptListData"
               :props="{ label: 'name', children: 'children' }"
               node-key="id"
               ref="dept-list-tree"
               :highlight-current="true"
               :expand-on-click-node="false"
               :default-expanded-keys="defaultDeptSelectList"
               show-checkbox
               check-strictly
               @check="deptListTreeChangeHandle"
               style="width:214px;overflow:hidden;">
      </el-tree>
    </el-popover>
    <el-select v-model="selectedDeptList"
               multiple
               collapse-tags
               v-popover:deptListPopover
               :readonly="true"
               @change="dropdownListChange"
               style="width:100%;"
               :placeholder="$t('custom.workSchedule.searchOrganization')">
    </el-select>
  </div>
</template>

<script>
import { BridgeComponent } from './bridgeComponent'
import { debounce } from 'lodash'

export default {
  data () {
    return {
      deptListVisible: false,
      deptListData: [],
      selectedDeptList: [],
      selectedDeptListData: [],
      defaultDeptSelectList: []
    }
  },
  mounted () {
    this.getDeptTree()
  },
  methods: {
    getDeptTree () {
      this.$interface.system.getDeptListApi()
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.deptListData = res.data
        }).catch(() => { })
    },
    deptListTreeChangeHandle (e, o) {
      this.selectedDeptListData = o.checkedNodes
      this.selectedDeptList = o.checkedNodes.map(i => {
        return i.name
      })
      this.updateOtherComponents(o.checkedKeys)
    },
    dropdownListChange (e) {
      let ids = []
      try {
        e.map(j => {
          this.selectedDeptListData.map(i => {
            if (i.name === j) {
              ids.push(i.id)
            }
          })
        })
      } catch (error) { }
      this.$refs['dept-list-tree'].setCheckedKeys(ids, true)
      this.selectedDeptList = e
      this.updateOtherComponents(ids)
    },
    updateOtherComponents: debounce(function (e) {
      this.$emit('resetSearch', e)
      BridgeComponent.$emit('updateScheduleUserList', e)
    }, 800),
    setInitDataForTree (initData) {
      let tree = this.$refs['dept-tree'].ej2Instances
      this.$emit('resetSearch', [initData])
      tree.value = [initData]
    },
    deptListTreeSetDefaultHandle () { }
  }
}
</script>

<style scoped>
</style>
